package com.njtoyo.taxi.admin.logic.business.ride;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.njtoyo.taxi.admin.library.common.Enum;
import com.njtoyo.taxi.admin.library.payment.ali.AliPayClient;
import com.njtoyo.taxi.admin.library.payment.cmb.CmbPayClient;
import com.njtoyo.taxi.admin.library.payment.common.CmbRefundInfo;
import com.njtoyo.taxi.admin.library.payment.common.PayBasicInfo;
import com.njtoyo.taxi.admin.library.payment.jyb.JybPayClient;
import com.njtoyo.taxi.admin.library.payment.wechat.WxPayClient;
import com.njtoyo.taxi.admin.logic.business.simple_call.RideTransactionLogLogic;
import com.njtoyo.taxi.admin.mapper.master.entity.*;
import com.njtoyo.taxi.admin.mapper.master.enums.*;
import com.njtoyo.taxi.admin.mapper.master.mapper.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import weixin.popular.bean.paymch.SecapiPayRefundResult;

import java.math.BigDecimal;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

@Service
@Slf4j
public class RideOrderLogic {

    @Autowired
    private RideOrderMapper rideOrderMapper;

    @Autowired
    private RefundMapper refundMapper;

    @Autowired
    private RideTransactionLogLogic rideTransactionLogLogic;

    @Autowired
    private RechargeMapper rechargeMapper;

    @Autowired
    private RefundLogic refundLogic;

    @Autowired
    private CouponMapper couponMapper;

    @Autowired
    private DriverFlowLogMapper driverFlowLogMapper;

    @Autowired
    private IncomeBelongingLogMapper incomeBelongingLogMapper;

    @Autowired
    private AliPayClient aliPayClient;

    @Autowired
    private WxPayClient wxPayClient;
    @Autowired
    private CallPrepayOrderMapper callPrepayOrderMapper;
    @Autowired
    private CallPrepayOrderRefundLogMapper callPrepayOrderRefundLogMapper;
    @Autowired
    private RideMapper rideMapper;
    @Autowired
    private DriverRegionServiceArrangementMapper driverRegionServiceArrangementMapper;
    @Autowired
    private DriverMapper driverMapper;

    public boolean offlineOrderSetOnline(Long rideId) {
        return new LambdaUpdateChainWrapper<>(rideOrderMapper)
                .eq(RideOrder::getRideId, rideId)
                .set(RideOrder::getActualAmount, null)
                .set(RideOrder::getFarePaid, null)
                .set(RideOrder::getBalancePaid, null)
                .set(RideOrder::getCouponId, null)
                .set(RideOrder::getTotalPaid, null)
                .set(RideOrder::getPresetThrough, RideOrderPaidThrough.online)
                .set(RideOrder::getPaidThrough, null).set(RideOrder::getLastPayTime, null)
                .set(RideOrder::getRefunded, false).set(RideOrder::getState, RideOrderState.init)
                .set(RideOrder::getUpdatedAt, new Date()).update();
    }

    public boolean onlineOrderSetOffline(Long rideId, RideOrder rideOrder) {
        return new LambdaUpdateChainWrapper<>(rideOrderMapper).eq(RideOrder::getRideId, rideId)
                .set(RideOrder::getPresetThrough, RideOrderPaidThrough.cash)
                .set(RideOrder::getState, RideOrderState.done).set(RideOrder::getPaidThrough, RideOrderPaidThrough.cash)
                .set(RideOrder::getActualAmount, rideOrder.getAmount()).set(RideOrder::getFarePaid, rideOrder.getAmount())
                .set(RideOrder::getCouponId, null).set(RideOrder::getAllowanceAmount, null).set(RideOrder::getAllowanceRefId, null)
                .set(RideOrder::getBalancePaid, 0).set(RideOrder::getRefunded, false)
                .set(Objects.isNull(rideOrder.getLastPayTime()), RideOrder::getLastPayTime, new Date())
                .set(RideOrder::getTotalPaid, rideOrder.getAmount())
                .set(RideOrder::getUpdatedAt, new Date()).update();
    }

    public boolean updateOrderAmount(Long rideId, BigDecimal amount) {
        return new LambdaUpdateChainWrapper<>(rideOrderMapper).eq(RideOrder::getRideId, rideId).ne(RideOrder::getState, RideOrderState.done).set(RideOrder::getAmount, amount).set(RideOrder::getUpdatedAt, new Date()).update();
    }

    // 判断行程是否有未付款的订单
    public boolean hasUnpaidOrder(Long rideId) {
        return Objects.nonNull(getUnpaidOrderByRideId(rideId));
    }

    // 判断行程是否有未付款的订单
    public RideOrder getUnpaidOrderByRideId(Long rideId) {
        RideOrder rideOrder = getOneRideOrderByRideId(rideId);

        if (Objects.nonNull(rideOrder) && !RideOrderState.done.equals(rideOrder.getState())) {
            return rideOrder;
        }

        return null;
    }

    // 根据rideId获取一个rideOrder
    public RideOrder getOneRideOrderByRideId(Long rideId) {
        List<RideOrder> list = new LambdaQueryChainWrapper<>(rideOrderMapper).eq(RideOrder::getRideId, rideId).orderByDesc(RideOrder::getId).list();

        if (Objects.nonNull(list)) {
            Optional<RideOrder> first = list.stream().findFirst();
            if (first.isPresent()) {
                return first.get();
            }
        }

        return null;
    }

    public boolean initRefund(RideOrder order, String refundableType) {
        Refund refund = new Refund();

        refund.setCustomerId(order.getUserId());
        refund.setNumber(refundLogic.getSnowflakeId());
        refund.setAmount(order.getAmount());
        refund.setFarePaidAmount(order.getFarePaid());
        refund.setState(RefundState.init);
        refund.setRefundableType(refundableType);
        refund.setRefundableId(order.getId());

        if (hasSavingPaid(order)) {
            log.info("rideOrderLogic:initRefund:有余额支付支付");
            RideTransactionLog log = rideTransactionLogLogic.getLogByRideOrderId(order.getId());
            Recharge recharge = rechargeMapper.selectById(log.getRechargeId());

            refund.setBalancePayAmount(recharge.getPayAmount());
            refund.setBalanceDonateAmount(recharge.getDonationAmount());
        } else {
            log.info("rideOrderLogic:initRefund:没有余额支付支付");
            refund.setBalancePayAmount(BigDecimal.ZERO);
            refund.setBalanceDonateAmount(BigDecimal.ZERO);
        }

        return refundMapper.insert(refund) > 0;
    }

    // 判断行程订单是否包含余额支付的记录
    public boolean hasSavingPaid(RideOrder order) {
        log.info("判断行程订单是否包含余额支付的记录");

        if (!RideOrderState.done.equals(order.getState())) {
            return false;
        }

        RideTransactionLog rideTransactionLog = rideTransactionLogLogic.getLogByRideOrderId(order.getId());
        log.info(String.format("rideTransactionLog:[%s]", rideTransactionLog));

        if (Objects.isNull(rideTransactionLog) || Objects.isNull(rideTransactionLog.getRechargeId())) {
            log.info("rideTransactionLog 或 rideTransactionLog.getRechargeId() 为空");
            return false;
        }

        Recharge recharge = rechargeMapper.selectById(rideTransactionLog.getRechargeId());
        if (Objects.isNull(recharge)) {
            return false;
        }

        return Objects.nonNull(rideTransactionLog.getBalancePaid()) && rideTransactionLog.getBalancePaid().compareTo(BigDecimal.ZERO) > 0;
    }

    // 判断行程订单是否包含卡券抵扣的记录
    public boolean hasCouponPaid(RideOrder order) {
        return Objects.nonNull(getHasCouponPaid(order));
    }

    // 判断行程订单是否包含卡券抵扣的记录[并获取]
    public Coupon getHasCouponPaid(RideOrder order) {
        if (!RideOrderState.done.equals(order.getState())) {
            return null;
        }

        if (Objects.isNull(order.getCouponId())) {
            log.info("没有卡券抵扣的记录");
            return null;
        }

        Coupon coupon = couponMapper.selectById(order.getCouponId());

        log.info(String.format("有卡券抵扣的记录：[%s]", coupon));

        if (Objects.nonNull(coupon) && coupon.getHadUsed()) {
            return coupon;
        }

        return null;
    }


    // 判断行程订单是否包含第三方支付实付的记录
    public boolean hasFarePaid(RideOrder rideOrder) {
        if (!RideOrderState.done.equals(rideOrder.getState())) {
            return false;
        }

        RideTransactionLog log = rideTransactionLogLogic.getLogByRideOrderId(rideOrder.getId());
        if (Objects.isNull(log) || Objects.isNull(log.getPayAmount()) || Objects.isNull(log.getPayThrough())) {
            return false;
        }

        List<RideOrderPaidThrough> payThroughList = new ArrayList<>();
        payThroughList.add(RideOrderPaidThrough.wxapp);
        payThroughList.add(RideOrderPaidThrough.wechat);
        payThroughList.add(RideOrderPaidThrough.alipay);
        payThroughList.add(RideOrderPaidThrough.jybwxapp);
        payThroughList.add(RideOrderPaidThrough.unionpay);

        return log.getPayAmount().compareTo(BigDecimal.ZERO) > 0 && payThroughList.contains(log.getPayThrough());
    }

    // 发起支付宝退款
    public boolean initiateAlipayRefund(RideOrder order) {
        log.info(String.format("发起支付宝退款，RideOrder：[%s]", order));

        Refund refund = refundLogic.getByRideOrderId(order.getId(), "RideOrder");

        if (Objects.nonNull(refund)) {
            PayBasicInfo payBasicInfo = new PayBasicInfo();

            payBasicInfo.setOutTradeNo(order.getNumber());
            payBasicInfo.setRefundAmount(order.getFarePaid());
            payBasicInfo.setRufundNo(refund.getNumber());

            // 调用alipay sdk
            return aliPayClient.refund(payBasicInfo);
        }

        return false;
    }

    // 发起微信小程序、APP退款
    public boolean initiateWeChatRefund(RideOrder order, Enum.RideRefundWxAppType wxAppType) {
        log.info(String.format("发起微信退款，RideOrder：[%s]；类型：[%s]", order, wxAppType));

        Refund refund = refundLogic.getByRideOrderId(order.getId(), "RideOrder");

        if (Objects.nonNull(refund)) {
            PayBasicInfo payBasicInfo = new PayBasicInfo();

            payBasicInfo.setWxAppType(wxAppType);

            payBasicInfo.setOutTradeNo(order.getOutTradeNumber());
            payBasicInfo.setNumber(order.getNumber());
            payBasicInfo.setRufundNo(refund.getNumber());

            payBasicInfo.setAmount(order.getFarePaid().add(order.getInfoServiceAmount()));
            payBasicInfo.setRefundAmount(order.getFarePaid());


            SecapiPayRefundResult refundResult = wxPayClient.refund(payBasicInfo);
            // 微信支付退款接口返回数据验签;
            if (refundResult.getSign_status() != null && refundResult.getSign_status()) {
                log.info("微信退款接口--接口请求状态(return_code):" + refundResult.getReturn_code());
                log.info("微信退款接口--接口请求状态(return_msg):" + refundResult.getReturn_msg());

                // 退款信息提交成功;
                if ("SUCCESS".equals(refundResult.getResult_code())) {
                    log.info("微信退款接口--接口请求状态(result_code):" + refundResult.getResult_code());
                    log.info("微信退款接口--接口请求状态(err_code):" + refundResult.getErr_code());
                    log.info("微信退款接口--接口请求状态(err_code_des):" + refundResult.getErr_code_des());

                    return true;
                }
            }

            return false;
        }

        return false;
    }

    // 发起微信小程序退款
    public boolean initiateJrcbWeChatRefund(RideOrder order, Enum.RideRefundWxAppType wxAppType) {
        log.info(String.format("发起招商退款，RideOrder：[%s]；类型：[%s]", order, wxAppType));
        Ride ride = rideMapper.selectById(order.getRideId());

        if (ObjectUtil.isNotNull(order.getPrepayAmount()) && order.getPrepayAmount().compareTo(BigDecimal.ZERO) == 1) {//预付款订单
            CallPrepayOrder callPrepayOrder = callPrepayOrderMapper.selectOne(Wrappers.<CallPrepayOrder>lambdaQuery()
                    .eq(CallPrepayOrder::getCallCategory, ride.getCategory().getCode()).
                    eq(CallPrepayOrder::getCallId, ride.getRefId()));
            BigDecimal addAmount = order.getFarePaid();
            if (addAmount.compareTo(BigDecimal.ZERO) == 1) {
                String addAmountStr = Convert.toStr(addAmount.multiply(new BigDecimal(100)).intValue());
                //退补充的钱
                Map<String, String> resultAddAmount = CmbPayClient.refund(getRefundId(), order.getNumber(), "退款", order.getNumber(), getRefundId(), addAmountStr, addAmountStr);
                String errCodeAddAmount = MapUtil.getStr(resultAddAmount, "errCode");
                if (StrUtil.isNotBlank(errCodeAddAmount)) {
                    String respMsg = MapUtil.getStr(resultAddAmount, "respMsg");
                    log.info("订单RideOrder：{},招商退预付款补充的钱返回--失败,失败原因：{}", order, respMsg);
                    return false;
                }
                String respCode = MapUtil.getStr(resultAddAmount, "respCode");
                if ("SUCCESS".equals(respCode)) {
                    log.info("订单RideOrder：{},招商退预付款补充的钱返回--成功,开始执行退预付款", order);
                    if (ObjectUtil.isNull(callPrepayOrder)) {
                        return true;
                    }
                    //退预付款的钱
                    String preAmountStr = Convert.toStr(order.getPrepayAmount().multiply(new BigDecimal(100)).intValue());
                    Map<String, String> resultPreAmount = CmbPayClient.refund(getRefundId(), callPrepayOrder.getNumber(), "退款", callPrepayOrder.getNumber(), getRefundId(), preAmountStr, preAmountStr);
                    String errCodePre = MapUtil.getStr(resultPreAmount, "errCode");
                    if (StrUtil.isNotBlank(errCodePre)) {
                        String respMsg = MapUtil.getStr(resultPreAmount, "respMsg");
                        log.info("订单RideOrder：{},招商退预付款返回--失败,失败原因：{}", order, respMsg);
                        return false;
                    }
                    String respPreCode = MapUtil.getStr(resultPreAmount, "respCode");
                    if ("SUCCESS".equals(respPreCode)) {
                        log.info("订单RideOrder：{},招商退预付款返回--成功", order);
                        //保存预付款的退款记录
                        callPrepayOrderRefundLogMapper.insert(new CallPrepayOrderRefundLog()
                                .setOrderId(callPrepayOrder.getId())
                                .setIsSuccess(true)
                                .setRefundAmount(order.getPrepayAmount())
                                .setRefundNumber(callPrepayOrder.getNumber()));
                        //修改预付款退款状态
                        callPrepayOrderMapper.updateById(new CallPrepayOrder().setId(callPrepayOrder.getId()).setIsRefund(true));
                        return true;
                    }
                }
            } else {
                List<CallPrepayOrderRefundLog> callPrepayOrderRefundLogs = callPrepayOrderRefundLogMapper.selectList(Wrappers.<CallPrepayOrderRefundLog>lambdaQuery()
                        .eq(CallPrepayOrderRefundLog::getOrderId, callPrepayOrder.getId()).eq(CallPrepayOrderRefundLog::getIsSuccess, true));
                BigDecimal reduce = callPrepayOrderRefundLogs.stream().map(CallPrepayOrderRefundLog::getRefundAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
                BigDecimal willRefund = NumberUtil.sub(callPrepayOrder.getAmount(), reduce);
                if (willRefund.compareTo(BigDecimal.ZERO) == 1) {
                    String resultPreAmountStr = Convert.toStr(willRefund.multiply(new BigDecimal(100)).intValue());
                    String txnAmtStr = Convert.toStr(callPrepayOrder.getAmount().multiply(new BigDecimal(100)).intValue());
                    Map<String, String> resultRefundAmount = CmbPayClient.refund(getRefundId(), callPrepayOrder.getNumber(), "退款", callPrepayOrder.getNumber(), getRefundId(), txnAmtStr, resultPreAmountStr);
                    String errCodeRefundAmount = MapUtil.getStr(resultRefundAmount, "errCode");
                    if (StrUtil.isNotBlank(errCodeRefundAmount)) {
                        String respMsg = MapUtil.getStr(resultRefundAmount, "respMsg");
                        log.info("订单RideOrder：{},招商退预付款补充的钱返回--失败,失败原因：{}", order, respMsg);
                        return false;
                    }
                    String respPreCode = MapUtil.getStr(resultRefundAmount, "respCode");
                    if ("SUCCESS".equals(respPreCode)) {
                        log.info("订单RideOrder：{},招商退预付款返回--成功", order);
                        //保存预付款的退款记录
                        callPrepayOrderRefundLogMapper.insert(new CallPrepayOrderRefundLog()
                                .setOrderId(callPrepayOrder.getId())
                                .setIsSuccess(true)
                                .setRefundAmount(willRefund)
                                .setRefundNumber(callPrepayOrder.getNumber()));
                        //修改预付款退款状态
                        callPrepayOrderMapper.updateById(new CallPrepayOrder().setId(callPrepayOrder.getId()).setIsRefund(true));
                        return true;
                    }
                }
            }
        } else {
            Refund refund = refundLogic.getByRideOrderId(order.getId(), "RideOrder");

            if (Objects.nonNull(refund)) {
                String orderId = IdUtil.getSnowflake(1, 1).nextIdStr();
                CmbRefundInfo refundInfo = new CmbRefundInfo();
                refundInfo.setOrderId(orderId);
                refundInfo.setOrigOrderId(order.getNumber());
                refundInfo.setSubOrderId(orderId);
                refundInfo.setSubOrigOrderId(order.getNumber());
                String amount = Convert.toStr(order.getFarePaid().multiply(new BigDecimal(100)).intValue());
                refundInfo.setTxnAmt(amount);
                refundInfo.setRefundAmt(amount);
                // 调用 sdk
                Map<String, String> result = CmbPayClient.refund(refundInfo);
                if (result == null) {
                    log.info("订单RideOrder：{},招商退款接口返回--失败", order);
                    return false;
                }
                String errCode = MapUtil.getStr(result, "errCode");
                if (StrUtil.isNotBlank(errCode)) {
                    String respMsg = MapUtil.getStr(result, "respMsg");
                    log.info("订单RideOrder：{},招商退款接口返回--失败,失败原因：{}", order, respMsg);
                    return false;
                }
                String respCode = MapUtil.getStr(result, "respCode");
                if ("SUCCESS".equals(respCode)) {
                    log.info("订单RideOrder：{},招商退款接口返回--成功", order);
                    return true;
                }
            }
        }
        return false;
    }

    private String getRefundId() {
        return IdUtil.getSnowflake(1, 1).nextIdStr();
    }

    // 判断行程订单是否已被退款
    public boolean hasBeenRefunded(RideOrder order) {
        return order.getRefunded();
    }

    // 检查行程订单是否已拥有初始化过的退款记录，如果发现拥有已完成的退款记录
    public boolean checkInitializedRefund(Long rideOrderId) {
        Refund refund = refundLogic.getByRideOrderId(rideOrderId, "RideOrder");

        return Objects.nonNull(refund) && !RefundState.done.equals(refund.getState());
    }

    // 获取行程订单实充余额支付金额
    public BigDecimal getPaySavingPaidAmount(Recharge recharge) {
        if (Objects.nonNull(recharge)) {
            return recharge.getPayAmount();
        }

        return BigDecimal.ZERO;
    }

    // 获取行程订单赠送余额支付金额
    public BigDecimal getDonationSavingPaidAmount(Recharge recharge) {
        if (Objects.nonNull(recharge)) {
            return recharge.getDonationAmount();
        }

        return BigDecimal.ZERO;
    }

    // 根据rideOrderId，删除对应司机收入流水
    public boolean deleteDriverFlowLogByOrderId(Long rideOrderId, DriverFlowLogCategory category) {
        LambdaQueryWrapper<DriverFlowLog> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DriverFlowLog::getCategory, category).eq(DriverFlowLog::getRefId, rideOrderId);

        return driverFlowLogMapper.delete(wrapper) > 0;
    }

    // 根据rideOrderId，删除对应公司分成流水
    public boolean deleteIncomeBelongingLogByOrderId(Long rideOrderId) {
        LambdaQueryWrapper<IncomeBelongingLog> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(IncomeBelongingLog::getRefCategory, IncomeBelongingLogCategory.ride_order).eq(IncomeBelongingLog::getRefId, rideOrderId);

        return incomeBelongingLogMapper.delete(wrapper) > 0;
    }

    // 根据rideOrderId，将 refund 记录的 state 设置为dong
    public boolean updateRefundStateDoneByOrderId(Long rideOrderId) {
        Refund refund = refundLogic.getByRideOrderId(rideOrderId, "RideOrder");

        if (Objects.isNull(refund)) {
            return false;
        }
        return new LambdaUpdateChainWrapper<>(refundMapper).eq(Refund::getId, refund.getId()).set(Refund::getState, RefundState.done).update();
    }

    public boolean checkInitializedDesignatedRefund(Long rideOrderId) {
        Refund refund = refundLogic.getByRideOrderId(rideOrderId, "DesignatedRideOrder");

        return Objects.nonNull(refund) && !RefundState.done.equals(refund.getState());
    }

    /**
     * 重新计算信息服务费
     *
     * @param ride
     * @return
     */
    public BigDecimal recountInfoAmount(Ride ride, BigDecimal updateAmount) {
//        RideOrder rideOrder = rideOrderMapper.selectOne(Wrappers.<RideOrder>lambdaQuery().eq(RideOrder::getRideId, ride.getId()));
//        if (ObjectUtil.isNull(rideOrder)) {
//            throw new RuntimeException("未找到行程订单");
//        }
        Driver driver = driverMapper.selectById(ride.getDriverId());
        DriverRegionServiceArrangement driverRegionServiceArrangement = driverRegionServiceArrangementMapper.selectOne(Wrappers.<DriverRegionServiceArrangement>lambdaQuery()
                .eq(DriverRegionServiceArrangement::getIsOpen, true)
                .eq(DriverRegionServiceArrangement::getDriverRegionId, driver.getDriverRegionId())
                .eq(DriverRegionServiceArrangement::getServiceCategory, DriverRegionServiceArrangementCategory.info_service_fee));
        if (ObjectUtil.isNull(driverRegionServiceArrangement)) {
            return BigDecimal.ZERO;
        }
        JSONObject jsonObject = JSON.parseObject(driverRegionServiceArrangement.getDetailSpecification());
        Date startDateTime = jsonObject.getDate("startTime");
        Date endDateTime = jsonObject.getDate("endTime");
        if (!DateUtil.isIn(DateUtil.date(), startDateTime, endDateTime)) {
            return BigDecimal.ZERO;
        }
        if (ride.getCategory() == RideCategory.appointment) {
            //预约单固定费用
            BigDecimal amount = jsonObject.getJSONObject("appointment").getBigDecimal("fee");
            return amount;
        } else if (ride.getCategory() == RideCategory.realtime) {
            JSONObject realtimeJson = JSON.parseObject(driverRegionServiceArrangement.getDetailSpecification()).getJSONObject("realtime");
            JSONObject peakHourJson = realtimeJson.getJSONObject("peakHour");
            JSONArray periodArray = peakHourJson.getJSONArray("period");
            LocalTime now = LocalTime.now();
            Boolean isMatch = periodArray.stream().anyMatch(period -> {
                JSONObject periodObj = (JSONObject) period;
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm");
                LocalTime startTime = LocalTime.parse(periodObj.getString("startTime"), formatter);
                LocalTime endTime = LocalTime.parse(periodObj.getString("endTime"), formatter);
                return now.isAfter(startTime) && now.isBefore(endTime);
            });
            if (isMatch) {
                //高峰期固定费用
                BigDecimal perFee = peakHourJson.getBigDecimal("perFee");
                BigDecimal maxFee = peakHourJson.getBigDecimal("maxFee");
                if (NumberUtil.mul(updateAmount, perFee).compareTo(maxFee) > 0) {
                    return maxFee;
                } else {
                    return NumberUtil.mul(updateAmount, perFee);
                }
            } else {
                JSONObject normalHourJson = realtimeJson.getJSONObject("normalHour");
                BigDecimal perFee = normalHourJson.getBigDecimal("perFee");
                BigDecimal maxFee = normalHourJson.getBigDecimal("maxFee");
                //非高峰期固定费用
                if (NumberUtil.mul(updateAmount, perFee).compareTo(maxFee) > 0) {
                    return maxFee;
                } else {
                    return NumberUtil.mul(updateAmount, perFee);
                }
            }
        }
        return BigDecimal.ZERO;
    }
}
